import { Component, OnInit } from '@angular/core';

import { Calendar, Params } from '../entity/Calendar';
import { CalendarService } from '../services/calendar.service';
import { ChatService } from '../services/chat.service';
import { EventSource, EventService, EventMessage } from '../services/event.service';

import {RequestReplyService} from '../services/request-reply.service';
import {Booked, BookedResult} from '../entity/TT';
import {OpenEvent} from '../booked/booked.component';

@Component({
  selector: 'app-record',
  templateUrl: './record.component.html',
  styleUrls: ['./record.component.scss']
})

export class RecordComponent implements OnInit {

  eventSource: EventSource = EventSource.RECORD_CALENDAR;
  result: BookedResult = BookedResult.completed;


  calendar: Calendar;
  activedDay: any;

  bookedList: object[];
  booked: any;

  constructor(
    private eventService: EventService,
    private calendarServer: CalendarService,
    private chatService: ChatService,
    private requestService: RequestReplyService,
  ) { }

  ngOnInit() {

    this.eventService.subscribeEvent((evt: EventMessage) => {
      const src = evt.source;
      if (src === this.eventSource) {
        this.activedDay = evt.data;
        this.loadBookedList( this.activedDay );
      }
    });
  }

  loadBookedList(day: any): void {
    const p = {day: new Date(day.localDate ).toISOString(), result: this.result };
    this.requestService.GetBookedList(p)
    .subscribe(bookedList => {
      day.bookedList = bookedList;
    });
  }

  loadMessage(booked: any): void {
    console.log('onSelectBooked:', booked);
    if (!(booked)) {
      return;
    }

    this.booked = booked;

    if (!(booked.id)) {
      return;
    }

    this.requestService.GetBookedMessage( booked )
    .subscribe( list => {
      booked.messageList = list;
    });

  }

  getSelectedDay() {
    const day = this.eventService.recordSelectedDay;
    return day;
  }

  onOpen(evt: OpenEvent) {
      console.log('open', evt);
      if (evt.isOpen) {
        this.loadMessage(evt.booked);
      }
  }

}
